/**
 * 入参
 *
 */
import React, { PureComponent } from 'react';
import { IconC, InputNumberC, ChildBenchMarkC } from '../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col } from 'antd';
import { connect } from 'dva';
const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 16,
  },
};
@Form.create()
class benchComponents extends PureComponent {
  state = {
    operatorNumberList: this.props.data,
  };
  componentDidMount() {
    this.props.onRef(this);
    this.setState({
      operatorNumberList: this.props.data,
    });
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.type != this.props.type && this.props.type && nextProps.type) {
      this.props.form.resetFields();
      this.props.form.setFieldsValue({ account: [{}] }); //operatorNumberList不能更新form表单，form表单也必须更新值，
      this.setState({
        operatorNumberList: [{}],
      });
    }
  }
  // 加
  add = () => {
    const nextList = this.state.operatorNumberList.concat({});
    this.props.form.setFieldsValue({ account: [...nextList] }); //operatorNumberList不能更新form表单，form表单也必须更新值，否则增减都会有问题
    this.setState({
      operatorNumberList: [...nextList],
    });
  };
  // 删除
  del = (index) => {
    if (this.state.operatorNumberList.length === 1) {
      //剩余一条不可删除
      return;
    }
    const nextList = this.state.operatorNumberList.filter((item, key) => key !== index);
    this.props.form.setFieldsValue({ account: [...nextList] }); //operatorNumberList不能更新form表单，form表单也必须更新值，否则增减都会有问题
    this.setState({
      operatorNumberList: [...nextList],
    });
  };
  //抛出数据
  getInfo = () => {
    let obj;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        obj = values;
      }
    });
    return obj;
  };
  //校验子基准是否重复
  checkIsSame = (rule, value, callback, index) => {
    const {
      form: { getFieldsValue, validateFields },
    } = this.props;
    const tempArr = getFieldsValue().account;
    //  除自己外的所有数据
    const arr = [];
    // 自己本条数据
    let myflag = false; //false:其他子基准 true:自定义子基准
    tempArr.map((item, key) => {
      if (key != index) {
        //除去自己 比对是否有重复
        let obj = JSON.parse(JSON.stringify(item));
        obj.key = key;
        arr.push(obj);
      } else {
        if (item.benchId) {
          myflag = true;
        }
      }
    });
    if (!value) {
      callback();
    } else {
      if (myflag) {
        // 自定义子基准
        if (arr?.find((item) => item.benchId == value && value)) {
          callback('子基准不能重复');
        } else {
          callback();
        }
      } else {
        // 其他子基准
        if (arr?.find((item) => item.wind == value && value)) {
          callback('子基准不能重复');
        } else {
          callback();
        }
      }
    }
  };

  //所有权重加起来是否等于100
  checkAddWeight = (rule, value, callback, index) => {
    const {
      form: { getFieldsValue },
    } = this.props;
    const tempArr = getFieldsValue().account;
    if (!value && value !== 0) {
      callback();
    } else {
      if (Number(value) == 0 || Number(value) == 100) {
        callback('子基准比例不能为0或100');
      } else {
        let sum = 0;
        tempArr.forEach((item) => {
          sum += Number(item.weight);
        });
        if (sum != 100) {
          // 子基准比例总和应为100
          callback('子基准比例总和应为100');
        } else {
          callback();
        }
      }
    }
  };
  // 其他类型子基准校验
  chechOther = (rule, value, callback, index) => {
    const {
      form: { getFieldsValue },
      type,
    } = this.props;
    const tempArr = getFieldsValue().account;
    if (type == '市值加权') {
      if (!value) {
        callback();
      } else {
        // 校验子基准是否重复

        //  除自己外的所有数据
        const arr = [];
        tempArr.map((item, key) => {
          if (key != index) {
            //除去自己 比对是否有重复
            let obj = JSON.parse(JSON.stringify(item));
            obj.key = key;
            arr.push(obj);
          }
        });
        if (arr?.find((item) => item.wind == value && value)) {
          callback('子基准不能重复');
        } else {
          callback();
        }
      }
    } else {
      callback();
    }
  };
  // 其他子基准更新数据
  onOtherChange = (index, name, event, field) => {
    const { operatorNumberList } = this.state;
    this.field = field;
    let tempArr = [...operatorNumberList];
    if (!event) {
      if (this.props.type == '单一') {
        if (name == 'wind') {
          // 其他子基准
          tempArr[index] = { ...tempArr[index], wind: undefined, benchId: undefined, weight: 1 };
        }
      } else {
        if (name == 'wind') {
          // 其他子基准
          tempArr[index] = { ...tempArr[index], wind: undefined, benchId: undefined, weight: null };
        }
      }
    } else {
      if (this.props.type == '单一') {
        if (name == 'wind') {
          // 其他子基准
          tempArr[index] = { ...tempArr[index], wind: event.key, benchId: undefined, weight: 1 };
        }
      } else {
        if (name == 'wind') {
          // 其他子基准
          tempArr[index] = { ...tempArr[index], wind: event.key, benchId: undefined, weight: null };
        }
      }
    }

    this.setState({
      operatorNumberList: [...tempArr],
    });
  };
  //复合类型更新数据
  onChange = (index, name, event, field) => {
    const { operatorNumberList } = this.state;
    this.field = field;
    let tempArr = [...operatorNumberList];
    if (!event) {
      if (name !== 'weight') {
        tempArr[index] = { ...tempArr[index], wind: undefined, benchId: undefined };
      } else if (name === 'weight') {
        // 权重
        tempArr[index] = { ...tempArr[index], weight: event };
      }
    } else {
      if (name !== 'weight') {
        if (event.flag == 1) {
          // 自定义的子基准
          tempArr[index] = { ...tempArr[index], benchId: event.key, wind: undefined };
        } else {
          // 其他子基准
          tempArr[index] = { ...tempArr[index], wind: event.key, benchId: undefined };
        }
      } else if (name === 'weight') {
        // 权重
        tempArr[index] = { ...tempArr[index], weight: event };
      }
    }

    this.setState(
      {
        operatorNumberList: [...tempArr],
      },
      () => {
        this.props.form.validateFields([`account[${index}].wind`, `account[${index}].benchId`], (errors) => {});
      },
    );
  };

  render() {
    const { isEdit, type } = this.props;
    return (
      <div style={{ overflow: 'hidden' }}>
        {type == '复合' ? (
          <>
            <div>
              {this.state.operatorNumberList
                ? this.state.operatorNumberList &&
                  this.state.operatorNumberList.map((item, index) => {
                    return (
                      <Row key={index}>
                        <Col span={13}>
                          <InputNumberC
                            form={this.props.form}
                            dataIndex={`account[${index}].weight`}
                            min={0}
                            max={100}
                            precision={2}
                            unit='%'
                            title={index == '0' ? '基准构成' : ' '}
                            initialValue={item.weight}
                            disabled={isEdit == 'check' ? true : false}
                            addClassName={index == '0' ? false : true}
                            formItemLayout={{
                              labelCol: {
                                xs: { span: 11, offset: 0 },
                                md: { span: 11, offset: 0 },
                                lg: { span: 11, offset: 0 },
                                xl: { span: 11, offset: 0 },
                                xxl: { span: 11, offset: 0 },
                              },
                              wrapperCol: {
                                xs: { span: 12, offset: 0 },
                                md: { span: 12, offset: 0 },
                                lg: { span: 12, offset: 0 },
                                xl: { span: 12, offset: 0 },
                                xxl: { span: 12, offset: 0 },
                              },
                            }}
                            rules={[{ required: true, message: `子基准比例不能为空` }, { validator: (rule, value, callback) => this.checkAddWeight(rule, value, callback, index) }]}
                            onChange={(event) => this.onChange(index, 'weight', event, `account[${index}].weight`)}
                          />
                        </Col>
                        <Col span={9}>
                          <div style={{ paddingBottom: ' 8px' }}>
                            {item.benchId ? (
                              <ChildBenchMarkC
                                title={''}
                                form={this.props.form}
                                dataIndex={`account[${index}].benchId`}
                                disabled={isEdit == 'check' ? true : false}
                                initialValue={item?.benchId ? item?.benchId : undefined}
                                showSearch={true}
                                allowClear={true}
                                includeBench={1}
                                keyFlag={true}
                                rules={[{ required: true, message: `基准构成不能为空` }, { validator: (rule, value, callback) => this.checkIsSame(rule, value, callback, index) }]}
                                onChange={(event) => this.onChange(index, 'benchId', event, `account[${index}].benchId`)}
                              />
                            ) : (
                              <ChildBenchMarkC
                                title={''}
                                form={this.props.form}
                                dataIndex={`account[${index}].wind`}
                                keyFlag={false}
                                disabled={isEdit == 'check' ? true : false}
                                initialValue={item?.wind ? item?.wind : undefined}
                                showSearch={false}
                                allowClear={true}
                                includeBench={1}
                                rules={[{ required: true, message: `基准构成不能为空` }, { validator: (rule, value, callback) => this.checkIsSame(rule, value, callback, index) }]}
                                onChange={(event) => this.onChange(index, 'wind', event, `account[${index}].wind`)}
                              />
                            )}
                          </div>
                        </Col>
                        {this.state.operatorNumberList.length <= 1 ? (
                          ''
                        ) : isEdit == 'check' ? (
                          ''
                        ) : (
                          <IconC
                            type={'minus'}
                            onClick={() => {
                              isEdit == 'check' ? '' : this.del(index);
                            }}
                            style={{ margin: '10px' }}
                          />
                        )}
                      </Row>
                    );
                  })
                : ''}
            </div>
          </>
        ) : type == '自定义' || type == '市值加权' || type == '单一' ? (
          <>
            <div>
              {this.state.operatorNumberList
                ? this.state.operatorNumberList &&
                  this.state.operatorNumberList.map((item, index) => {
                    return (
                      <Row key={index}>
                        <Col span={24}>
                          <div style={{ paddingBottom: ' 8px' }}>
                            <ChildBenchMarkC
                              title={index == '0' ? '基准构成' : ' '}
                              form={this.props.form}
                              dataIndex={`account[${index}].wind`}
                              disabled={isEdit == 'check' ? true : false}
                              initialValue={item?.wind ? item?.wind : undefined}
                              showSearch={false}
                              allowClear={true}
                              includeBench={0}
                              formItemLayout={formItemLayout}
                              addClassName={index == '0' ? false : true}
                              rules={[{ required: true, message: `基准构成不能为空` }, { validator: (rule, value, callback) => this.chechOther(rule, value, callback, index) }]}
                              onChange={(event) => this.onOtherChange(index, 'wind', event, `account[${index}].wind`)}
                            />
                          </div>
                        </Col>
                        {this.state.operatorNumberList.length <= 1 ? (
                          ''
                        ) : isEdit == 'check' ? (
                          ''
                        ) : (
                          <IconC
                            type={'minus'}
                            style={{ margin: '10px', position: 'absolute', right: '0px', top: '2px' }}
                            onClick={() => {
                              isEdit == 'check' ? '' : this.del(index);
                            }}
                          />
                        )}
                      </Row>
                    );
                  })
                : ''}
            </div>
          </>
        ) : (
          ''
        )}

        {type == '复合' || type == '市值加权' ? (
          isEdit == 'check' ? (
            ''
          ) : (
            <IconC
              type={'plus'}
              onClick={() => {
                this.props.isEdit == 'check' ? '' : this.add();
              }}
              style={{ marginLeft: '24.5%', marginBottom: '16px' }}
            />
          )
        ) : (
          ''
        )}
      </div>
    );
  }
}
export default connect(({ BaselineInformationNewM }) => ({
  BaselineInformationNewM,
}))(benchComponents);
